package easy;

public class Solution_606 {

    private StringBuffer buffer = new StringBuffer();

    public String tree2str(TreeNode root) {
        if (root == null) {
            return "";
        }
        dps(root);
        return buffer.toString();
    }

    private void dps(TreeNode node) {
        buffer.append(node.val);
        if (node.left!=null || node.right != null) {
            buffer.append("(");
            if (node.left!=null) {
                dps(node.left);
            }
            buffer.append(")");
            if (node.right!=null) {
                buffer.append("(");
                dps(node.right);
                buffer.append(")");
            }
        } else {
            return;
        }
    }

    public static void main(String[] args) {
        Solution_606 model = new Solution_606();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(4);
        root.right = new TreeNode(3);
        System.out.println(model.tree2str(root));
    }

    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
